package me.jiatao.viewmodel

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.liveData
import kotlinx.coroutines.*

class SecondActivity : AppCompatActivity() {
    private val coroutineView: TextView by lazy {
        findViewById(R.id.coroutine_text)
    }

    private val liveIndex: LiveData<String> by lazy {
        liveData {
            for (index in 1..Int.MAX_VALUE) {
                delay(500)
                emit("current $index")
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
    }

    fun startCoroutine(view: View) {
        lifecycleScope.launch {
            for (index in 1..Int.MAX_VALUE) {
                val str = withContext(Dispatchers.IO) {
                    delay(500)
                    //运行在IO线程
                    println("withContext ${Thread.currentThread().name}")
                    "hello $index"
                }

                //运行在主线程
                println("launch ${Thread.currentThread().name}")
                coroutineView.text = str
            }
        }

        liveIndex.observe(this, {
            println(it)
            coroutineView.text = it
        })

    }
}